package com.xiuyi.pixsynergybackend.controller.picture;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiuyi.pixsynergybackend.annotation.AuthCheck;
import com.xiuyi.pixsynergybackend.common.BaseResponse;
import com.xiuyi.pixsynergybackend.common.DeleteRequest;
import com.xiuyi.pixsynergybackend.common.ResultUtils;
import com.xiuyi.pixsynergybackend.constant.UserConstant;
import com.xiuyi.pixsynergybackend.controller.picture.vo.*;
import com.xiuyi.pixsynergybackend.dal.dataobject.picture.PictureDO;
import com.xiuyi.pixsynergybackend.dal.dataobject.user.UserDO;
import com.xiuyi.pixsynergybackend.exception.BusinessException;
import com.xiuyi.pixsynergybackend.exception.ErrorCode;
import com.xiuyi.pixsynergybackend.exception.ThrowUtils;
import com.xiuyi.pixsynergybackend.service.picture.PictureService;
import com.xiuyi.pixsynergybackend.service.user.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/picture")
public class PictureController {

    @Resource
    private UserService userService;

    @Resource
    private PictureService pictureService;

    /**
     * 上传图片（可重新上传）
     */
    @PostMapping("/upload")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<PictureVO> uploadPicture(@RequestPart("file") MultipartFile multipartFile, PictureUploadReqVO pictureUploadReqVO,
                                                 HttpServletRequest request) {
        UserDO loginUser = userService.getLoginUser(request);
        PictureVO pictureVO = pictureService.uploadPicture(multipartFile, pictureUploadReqVO, loginUser);
        return ResultUtils.success(pictureVO);
    }

    /**
     * 删除图片
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deletePicture(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null && deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserDO loginUser = userService.getLoginUser(request);
        Long id = deleteRequest.getId();
        // 判断图片是否存在
        PictureDO oldPictureDO = pictureService.getById(id);
        ThrowUtils.throwIf(oldPictureDO == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldPictureDO.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = pictureService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 更新图片（仅管理员可用）
     *
     * @param pictureUpdateReqVO
     * @param request
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updatePicture(@RequestBody PictureUpdateReqVO pictureUpdateReqVO, HttpServletRequest request) {
        if (pictureUpdateReqVO == null && pictureUpdateReqVO.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 将 VO 转换为 DO
        PictureDO pictureDO = new PictureDO();
        BeanUtils.copyProperties(pictureUpdateReqVO, pictureDO);
        // 将 list 转换为 String
        pictureDO.setTags(JSONUtil.toJsonStr(pictureDO.getTags()));
        // 数据校验
        pictureService.validPicture(pictureDO);
        // 判断是否存在
        Long id = pictureUpdateReqVO.getId();
        PictureDO oldPictureDO = pictureService.getById(id);
        ThrowUtils.throwIf(oldPictureDO == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = pictureService.updateById(pictureDO);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据id获取图片（仅管理员可用）
     *
     * @param id
     * @return
     */
    @PostMapping("/get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<PictureDO> getPictureDOById(long id) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 根据id查询数据库
        PictureDO pictureDO = pictureService.getById(id);
        ThrowUtils.throwIf(pictureDO == null, ErrorCode.NOT_FOUND_ERROR);
        // 返回
        return ResultUtils.success(pictureDO);
    }


    /**
     * 根据id获取图片（返回vo）
     *
     * @param id
     * @param request
     * @return
     */
    @PostMapping("/get/vo")
    public BaseResponse<PictureVO> getPictureVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 根据id查询数据库
        PictureDO pictureDO = pictureService.getById(id);
        ThrowUtils.throwIf(pictureDO == null, ErrorCode.NOT_FOUND_ERROR);
        // 返回
        return ResultUtils.success(pictureService.getPictureVO(pictureDO, request));
    }

    /**
     * 分页获取图片列表（仅管理员可用）
     *
     * @param pictureQueryReqVO
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<PictureDO>> listPictureDOPage(@RequestBody PictureQueryReqVO pictureQueryReqVO) {
        int current = pictureQueryReqVO.getCurrent();
        int size = pictureQueryReqVO.getPageSize();
        // 查询数据库
        Page<PictureDO> pictureDOPage = pictureService.page(new Page<>(current, size),
                pictureService.getQueryWrapper(pictureQueryReqVO));
        return ResultUtils.success(pictureDOPage);
    }

    /**
     * 分页获取图片列表（返回vo）
     *
     * @param pictureQueryReqVO
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<PictureVO>> listPictureVOPage(@RequestBody PictureQueryReqVO pictureQueryReqVO,
                                                           HttpServletRequest request) {
        int current = pictureQueryReqVO.getCurrent();
        int size = pictureQueryReqVO.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<PictureDO> pictureDOPage = pictureService.page(new Page<>(current, size),
                pictureService.getQueryWrapper(pictureQueryReqVO));
        return ResultUtils.success(pictureService.getPictureVOPage(pictureDOPage, request));
    }

    /**
     * 编辑图片（仅管理员可用）
     *
     * @param pictureEditReqVO
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editPicture(@RequestBody PictureEditReqVO pictureEditReqVO, HttpServletRequest request) {
        if (pictureEditReqVO == null && pictureEditReqVO.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // vo 转换为 do
        PictureDO pictureDO = new PictureDO();
        BeanUtils.copyProperties(pictureEditReqVO, pictureDO);
        // 将 list 转换为 string
        pictureDO.setTags(JSONUtil.toJsonStr(pictureEditReqVO.getTags()));
        // 设置编辑时间
        pictureDO.setEditTime(new Date());
        // 数据校验
        pictureService.validPicture(pictureDO);
        UserDO loginUser = userService.getLoginUser(request);
        // 判断是否存在
        Long id = pictureEditReqVO.getId();
        PictureDO oldPictureDO = pictureService.getById(id);
        ThrowUtils.throwIf(oldPictureDO == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldPictureDO.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = pictureService.updateById(pictureDO);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 返回预设的标签、分类数据
     *
     * @return
     */
    @GetMapping("/tag_category")
    public BaseResponse<PictureTagCategoryVO> listPictureTagCategory() {
        PictureTagCategoryVO pictureTagCategoryVO = new PictureTagCategoryVO();
        List<String> tagList = Arrays.asList("热门", "搞笑", "生活", "高清", "艺术", "校园", "背景", "简历", "创意");
        List<String> categoryList = Arrays.asList("模板", "电商", "表情包", "素材", "海报");
        pictureTagCategoryVO.setTagList(tagList);
        pictureTagCategoryVO.setCategoryList(categoryList);
        return ResultUtils.success(pictureTagCategoryVO);
    }

}
